﻿using AVCUMPlatform.BLL.Implement;
using AVCUMPlatform.BLL.Interface;
using AVCUMPlatform.BLL;
using AVCUMPlatform.Entities;
using AVCUMPlatform.Models;
using Microsoft.AspNetCore.Mvc;
using AVCUMPlatform.Entities.Enum;
using AVCUMPlatform.HelperLibrary;
using HelperLibrary;
using Newtonsoft.Json;
using AVCUMPlatform.WXService.Model;

namespace AVCUMPlatform.Controllers
{
    /// <summary>
    /// 消息模板接口
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class MessageTmplatesController : ControllerBase
    {
        private IMessageTmplatesBLL _messageTemplatesBLL = BLLContainer.Resolve<IMessageTmplatesBLL>();
        private IMessageTypesBLL _messageTypesBll = BLLContainer.Resolve<IMessageTypesBLL>();
        private IClientInfoBLL _clientInfoBll = BLLContainer.Resolve<IClientInfoBLL>();
        /// <summary>
        /// 分页查询消息模板
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="field">排序字段</param>
        /// <param name="order">排序方式</param>
        /// <returns></returns>
        [HttpGet]
        [NoNeedLogin]
        public ActionResult GetList(int page, int limit, string? field, string? order)
        {
            var vmList = new List<MessageTmplatesVM>();
            try
            {
                var clientInfoList = _clientInfoBll.GetAll().Where(x => x.ClientType == (int)ClientTypeEnum.WX || x.ClientType == (int)ClientTypeEnum.MINIWX).ToList();
                if (clientInfoList != null && clientInfoList.Any())
                {
                    foreach (var clientInfo in clientInfoList)
                    {
                        string cacheKey = $"WXTemplateKey_{clientInfoList.IndexOf(clientInfo) + 1}";
                        var wxTemplatesExists = CacheHelper.Exists(cacheKey);
                        if (!wxTemplatesExists)
                        {
                            AllPrivateTemplates? allPrivateTemplates = null;
                            if (clientInfo.ClientType == (int)ClientTypeEnum.WX)
                            {
                                allPrivateTemplates = ApiHelperFactory.GetWXInstance(clientInfo.Source).GetAllPrivateTemplate();
                            }
                            else
                            {
                                allPrivateTemplates = ApiHelperFactory.GetMiniWXInstance(clientInfo.Source).GetAllPrivateTemplate();
                            }
                            if (allPrivateTemplates != null && allPrivateTemplates.template_list != null && allPrivateTemplates.template_list.Any())
                            {
                                foreach (var template in allPrivateTemplates.template_list)
                                {
                                    var existTemplate = _messageTemplatesBLL.GetAll().FirstOrDefault(x => x.TemplateId == template.template_id);
                                    if (existTemplate == null || existTemplate.Id <= 0)
                                    {
                                        var model = new MessageTmplates()
                                        {
                                            Name = template.title,
                                            TemplateId = template.template_id,
                                            Content = template.content,
                                            Example = template.example,
                                            CreateTime = DateTime.Now.ToYMDHMS(),
                                            Enable = 1
                                        };
                                        _messageTemplatesBLL.Add(model);
                                    }
                                }
                                CacheHelper.Set(cacheKey, allPrivateTemplates, TimeSpan.FromHours(8));
                            }
                        }
                    }
                }

                var list = _messageTemplatesBLL.GetAll();
                if (!string.IsNullOrWhiteSpace(field) && field != "undefined")
                {
                    if (!string.IsNullOrWhiteSpace(order) && order != "undefined")
                    {
                        if (order == "desc")
                        {
                            if (field == "id")
                            {
                                list = list.OrderByDescending(x => x.Id).ToList();
                            }
                            else if (field == "createTime")
                            {
                                list = list.OrderByDescending(x => x.CreateTime).ToList();
                            }
                        }
                        else
                        {
                            if (field == "id")
                            {
                                list = list.OrderBy(x => x.Id).ToList();
                            }
                            else if (field == "createTime")
                            {
                                list = list.OrderBy(x => x.CreateTime).ToList();
                            }
                        }
                    }
                }
                var count = list.Count();
                list = list.Skip((page - 1) * limit).Take(limit).ToList();
                var msgTypes = _messageTypesBll.GetAll();
                foreach (var messageTmplate in list)
                {
                    var exist = msgTypes.FirstOrDefault(x => x.MessageTemplateId == messageTmplate.Id);
                    var vm = new MessageTmplatesVM()
                    {
                        Id = messageTmplate.Id,
                        TemplateId = messageTmplate.TemplateId,
                        Name = messageTmplate.Name,
                        Content = messageTmplate.Content.Replace("\\n", "\n"),
                        Example = messageTmplate.Example.Replace("\\n", "\n"),
                        SendJson = !string.IsNullOrWhiteSpace(messageTmplate.SendJson) ? messageTmplate.SendJson.Replace("{{template_id}}", messageTmplate.TemplateId) : string.Empty,
                        CreateTime = messageTmplate.CreateTime,
                        Enable = messageTmplate.Enable,
                        EnableStr = messageTmplate.Enable == 1 ? "启用" : "禁用",
                        IsCanDelete = exist == null || exist.Id <= 0 ? 1 : 2
                    };
                    vmList.Add(vm);
                }
                var obj = new { code = 0, count, data = vmList, msg = "" };
                return new JsonResult(obj);
            }
            catch (Exception ex)
            {
                Log.WriteException(ex);
                return new JsonResult(new { code = 0, count = 0, data = vmList, msg = "" });
            }
        }

        /// <summary>
        /// 查询所有消息模板
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [NoNeedLogin]
        public ActionResult GetAll()
        {
            var vmList = new List<MessageTmplatesVM>();
            var messageTmplates = _messageTemplatesBLL.GetAll();
            
            foreach (var messageTmplate in messageTmplates)
            {
                var vm = new MessageTmplatesVM()
                {
                    Id = messageTmplate.Id,
                    TemplateId = messageTmplate.TemplateId,
                    Name = messageTmplate.Name,
                    Content = messageTmplate.Content,
                    Example = messageTmplate.Example,
                    CreateTime = messageTmplate.CreateTime,
                    Enable = messageTmplate.Enable,
                    EnableStr = messageTmplate.Enable == 1 ? "启用" : "禁用"
                };
                vmList.Add(vm);
            }
            var obj = new { code = 0, count = vmList.Count, data = vmList, msg = "" };
            return new JsonResult(obj);
        }

        /// <summary>
        /// 新增或编辑
        /// </summary>
        /// <param name="messageTmplates"></param>
        /// <returns></returns>
        [HttpPost]
        [NoNeedLogin]
        public ResultModel AddOrUpdate(MessageTmplatesReq messageTmplates)
        {
            var ret = new ResultModel();
            if (messageTmplates.Id > 0)
            {
                var exist = _messageTemplatesBLL.Get(messageTmplates.Id);
                exist.Name = messageTmplates.Name;
                exist.Content = messageTmplates.Content;
                exist.Example = messageTmplates.Example;
                exist.ModifyTime = DateTime.Now.ToYMDHMS();
                exist.Enable = messageTmplates.Enable;
                exist.SendJson = messageTmplates.SendJson;
                _messageTemplatesBLL.Update(exist);
            }
            else
            {
                var addmodel = new MessageTmplates()
                {
                    Name = messageTmplates.Name,
                    Content = messageTmplates.Content,
                    Example = messageTmplates.Example,
                    SendJson = messageTmplates.SendJson,
                    CreateTime = DateTime.Now.ToYMDHMS(),
                    Enable = messageTmplates.Enable
                };
                _messageTemplatesBLL.Add(addmodel);
            }
            ret.code = 1;
            return ret;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [NoNeedLogin]
        public ResultModel Delete(int id)
        {
            var ret = new ResultModel();
            ret.code = _messageTemplatesBLL.Delete(new List<int>() { id }) ? 1 : -1;
            if (ret.code == -1)
            {
                ret.msg = "删除失败";
            }
            return ret;
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpGet]
        [NoNeedLogin]
        public ResultModel BatchDelete(string ids)
        {
            var ret = new ResultModel();
            var idList = ids.Split(',').Select(x => Convert.ToInt32(x)).ToList();
            ret.code = _messageTemplatesBLL.Delete(idList) ? 1 : -1;
            if (ret.code == -1)
            {
                ret.msg = "删除失败";
            }
            return ret;
        }

        /// <summary>
        /// 清理缓存
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public bool RemoveCache(string key = "WXTemplateKey")
        {
            CacheHelper.Remove(key);
            return true;
        }
    }
}
